import axios from 'axios';

const BASE_URL = 'http://117.72.106.234:8080/api/rag';

// 创建axios实例
const ragApi = axios.create({
  baseURL: BASE_URL,
  timeout: 30000, // 30秒超时，因为AI响应可能较慢
});

// 请求拦截器 - 添加认证token
ragApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理通用错误
ragApi.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // token过期，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

const ragService = {
  // 1. 创建聊天线程
  createThread: async (name = '') => {
    try {
      const response = await ragApi.post('/threads', { name });
      return response;
    } catch (error) {
      throw error;
    }
  },

  // 2. 获取聊天线程列表
  getThreads: async (pageNum = 1, pageSize = 10) => {
    try {
      const response = await ragApi.get('/threads', {
        params: { pageNum, pageSize }
      });
      return response;
    } catch (error) {
      throw error;
    }
  },

  // 3. 获取聊天历史
  getChatHistory: async (threadId) => {
    try {
      const response = await ragApi.get(`/threads/${threadId}/history`);
      return response;
    } catch (error) {
      throw error;
    }
  },

  // 4. 删除聊天线程
  deleteThread: async (threadId) => {
    try {
      const response = await ragApi.delete(`/threads/${threadId}`);
      return response;
    } catch (error) {
      throw error;
    }
  },

  // 5. 流式聊天 - 使用fetch API处理SSE
  streamChat: async (threadId, message, onMessage, onError, onComplete) => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${BASE_URL}/threads/${threadId}/stream-chat`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
        },
        body: JSON.stringify({ message })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      const readStream = async () => {
        try {
          const { done, value } = await reader.read();
          
          if (done) {
            onComplete && onComplete();
            return;
          }

          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;

          const lines = buffer.split('\n');
          buffer = lines.pop() || '';

          for (const line of lines) {
            if (line.startsWith('data:')) {
              const jsonData = line.substring(5).trim();
              if (jsonData) {
                try {
                  const data = JSON.parse(jsonData);
                  
                  if (data.error && data.error !== false) {
                    onError && onError(data.error);
                    return;
                  }
                  
                  onMessage && onMessage(data);
                  
                  if (data.close) {
                    onComplete && onComplete();
                    return;
                  }
                } catch (parseError) {
                }
              }
            }
          }

          // 继续读取下一个chunk
          await readStream();
        } catch (error) {
          onError && onError(error.message || '流式聊天连接中断');
        }
      };

      await readStream();
    } catch (error) {
      onError && onError(error.message || '发送消息失败');
    }
  }
};

export default ragService; 